//
//  SelectedGoodNewViewController.m
//  HAODE
//
//  Created by LiYinDi on 16/3/22.
//  Copyright © 2016年 reabam.com. All rights reserved.
//

#import "SelectedGoodNewViewController.h"
#import "SelectedGoodNewHeaderDataModel.h"
#import "FMDB.h"
#import "PlaceOrderSpecTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "specTableViewDataModel.h"
#import "Masonry.h"

#import "BusinessPOrderAddViewController.h"
#import "BusinessOrderExtAddViewController.h"
#import "BusinessWhsInAddViewController.h"
#import "HAODEsingleton.h"
#import "BusinessCheckVouchAddViewController.h"
#import "BusinessCheckVouchContinueViewController.h"
#import "BusinessOrderExtAddViewController.h"
//#import "BusinessNeedOrderAddViewController.h"
#import "ClearFB.h"
@interface SelectedGoodNewViewController ()<PlaceOrderSpecCellDelegate>
{
    NSMutableArray *headerModelArray;
    
    NSString *userToken;
    NSInteger parentTag;
    HAODEsingleton*commdity;
}
@property(nonatomic,strong)FMDatabase *userDB;
//@property(nonatomic,strong)FMDatabase *noSpecDB;
@end

@implementation SelectedGoodNewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    commdity=[HAODEsingleton shared];
    [self setNavigation];
    [self setAutoLayout];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    userToken = [user objectForKey:@"tokenId"];
    headerModelArray=[NSMutableArray array];
    
    //    [_totalCountView setBackgroundColor:[Global parseColor:@"#E01F3536"]];
    [self initDataBase];
    
    [self getTotalCountFromDB];
//    [self getTotalValue];
    
    CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
    CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
    _totalLabel.text=[NSString stringWithFormat:@"%0.02f",noSpectTotalMoney+hasSpectTotalMoney];
    // Do any additional setup after loading the view from its nib.
}
-(void)initDataBase
{
    NSString *dbPath = [self getDBPath];
    NSLog(@"dbPath===%@",dbPath);
    _userDB = [FMDatabase databaseWithPath:dbPath];
    if (![_userDB open]) {
        NSLog(@"open membersDB failed");
        return;
    }
    [self getNoSpecDataFromDB];
}

-(void)getTotalCountFromDB
{
    NSInteger count=0;
    //    PlaceOrderSubDataModel *model=modelArray[tag];
    FMResultSet *resultSet=[_userDB executeQuery:@"SELECT * FROM t_UserPlaceOrder WHERE userToken = ? AND typeString = ?;" ,userToken,_typeString];
    
    while (resultSet.next) {
        NSString *countString=[resultSet objectForColumnName:@"specCount"];
        count=count+[countString integerValue];
        
    }
    [resultSet close];
    _titleLabel.text=[NSString stringWithFormat:@"已选%ld件商品",(long)count];
    
}
-(CGFloat)getTotalMoneyFromNoSpecDB
{
    CGFloat totalNoSpecMoney=0;
    //    PlaceOrderSubDataModel *model=modelArray[tag];
    FMResultSet *resultSet=[_userDB executeQuery:@"SELECT * FROM t_UserPlaceOrder WHERE userToken = ? AND typeString = ? AND hasSpec = ? ;" ,userToken,_typeString,@"0"];
    
    while (resultSet.next) {
        NSString *countString=[resultSet objectForColumnName:@"specCount"];
        NSString *salePriceString=[resultSet objectForColumnName:@"salePrice"];
        totalNoSpecMoney=totalNoSpecMoney+[countString integerValue]*[salePriceString floatValue];
        
    }
    [resultSet close];
    return totalNoSpecMoney;
    
}
-(CGFloat)getTotalMoneyFromHasSpecDB
{
    CGFloat totalHasSpecMoney=0;
    //    PlaceOrderSubDataModel *model=modelArray[tag];
    FMResultSet *resultSet=[_userDB executeQuery:@"SELECT * FROM t_UserSpec WHERE userToken = ? AND typeString = ? ;" ,userToken,_typeString ];
    
    while (resultSet.next) {
        NSString *countString=[resultSet objectForColumnName:@"specCount"];
        
        NSString *salePriceString=[resultSet objectForColumnName:@"specPrice"];
        
        totalHasSpecMoney=totalHasSpecMoney+[countString integerValue]*[salePriceString floatValue];
        
    }
    [resultSet close];
    
    
    return totalHasSpecMoney;
    
}




-(void )getNoSpecDataFromDB
{
    
    FMResultSet *resultSet=[_userDB executeQuery:@"SELECT * FROM t_UserPlaceOrder WHERE userToken = ? AND typeString = ? ;" ,userToken,_typeString];
    
    while (resultSet.next) {
        SelectedGoodNewHeaderDataModel *model=[[SelectedGoodNewHeaderDataModel alloc] init];
        
        model.imageUrlFull=[resultSet objectForColumnName:@"imageUrlFull"];
        model.itemCode=[resultSet objectForColumnName:@"itemCode"];
        model.itemId=[resultSet objectForColumnName:@"itemId"];
        model.itemName=[resultSet objectForColumnName:@"itemName"];
        model.maxPrice=[resultSet objectForColumnName:@"maxPrice"];
        
        model.minPrice=[resultSet objectForColumnName:@"minPrice"];
        model.salePrice=[resultSet objectForColumnName:@"salePrice"];
        model.invQty=[resultSet objectForColumnName:@"invQty"];
        
        model.specType=[resultSet objectForColumnName:@"hasSpec"];
        model.specCount=[resultSet objectForColumnName:@"specCount"];
        model.isOpened = NO;
        
//        NSLog(@"model.imageUrlFull==%@",model.imageUrlFull);
        
        [headerModelArray addObject:model];
    }
    [resultSet close];
}
-(NSString *)getDBPath
{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *DBPath = [documentPath stringByAppendingPathComponent:kUserDBNAME];
//    NSLog(@"DBPath//==%@",DBPath);
    return DBPath;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[section];
    
    
    if ([headerModel.specType intValue]!=0) {
        UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth,122)];
        UIImageView *productImageView=[[UIImageView alloc] initWithFrame:CGRectMake(15, 20, 82, 82)];
        productImageView.layer.borderColor=[[UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1] CGColor];
        productImageView.layer.borderWidth= 1.0f;
       
        [productImageView setImageWithURL:[NSURL URLWithString:headerModel.imageUrlFull]];
        [view addSubview:productImageView];
        
        UILabel *productNameLabel=[[UILabel alloc] initWithFrame:CGRectMake(109, 20, ScreenWidth-116, 18)];
        [productNameLabel setText:headerModel.itemName];
        productNameLabel.font=[UIFont systemFontOfSize:14];
        productNameLabel.textColor=[UIColor colorWithRed:51.0/255.0f green:51.0/255.0f  blue:51.0/255.0f  alpha:1.0];
        [view addSubview:productNameLabel];
        
        UILabel *productPriceLabel=[[UILabel alloc] initWithFrame:CGRectMake(109, 46, 200, 15)];
        [productPriceLabel setText:[NSString stringWithFormat:@"¥%0.02f",[headerModel.salePrice floatValue]]];
        productPriceLabel.font=[UIFont systemFontOfSize:12];
        productPriceLabel.textColor=[UIColor colorWithRed:102.0/255.0f green:102.0/255.0f  blue:102.0/255.0f  alpha:1.0];
        
        [view addSubview:productPriceLabel];
        
        UILabel *productInvLabel=[[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth-122, 46,110, 15)];
        
        productInvLabel.font=[UIFont systemFontOfSize:12];
        productInvLabel.textColor=[UIColor colorWithRed:102.0/255.0f green:102.0/255.0f  blue:102.0/255.0f  alpha:1.0];
        NSString *str=[NSString stringWithFormat:@"库存 %d",[headerModel.invQty intValue]];
        NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:str];
        [attriString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1.0] range:NSMakeRange(0, 2)];
        
        productInvLabel.attributedText=attriString;
        
        productInvLabel.textAlignment=NSTextAlignmentRight;
        [view addSubview:productInvLabel];
        
        
        UILabel *productCountLabel=[[UILabel alloc] initWithFrame:CGRectMake(109, 85, 85, 15)];
        productCountLabel.font=[UIFont systemFontOfSize:14];
        productCountLabel.textColor=[UIColor colorWithRed:51.0/255.0f green:51.0/255.0f  blue:51.0/255.0f  alpha:1.0];
        
        //        [productCountLabel setText:];
        NSString *productCountStr=[NSString stringWithFormat:@"小计 %d",[headerModel.specCount intValue]];
        NSMutableAttributedString *productAttrIString = [[NSMutableAttributedString alloc] initWithString:productCountStr];
        [productAttrIString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0] range:NSMakeRange(0, 2)];
        
        productCountLabel.attributedText=productAttrIString;
        productCountLabel.textAlignment=NSTextAlignmentLeft;
        [view addSubview:productCountLabel];
        
        UIButton *detailBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        detailBtn.frame=CGRectMake(ScreenWidth-110, 72, 100, 30);
        detailBtn.layer.borderWidth=1.0;
        detailBtn.layer.borderColor=[UIColor colorWithRed:240.0/255.0f green:240.0/255.0f blue:240.0/255.0f alpha:240.0/255.0f].CGColor;
        detailBtn.tag=section;
         detailBtn.titleLabel.font = [UIFont systemFontOfSize: 14.0];
        if ( !headerModel.isOpened) {
            [detailBtn setImage:[UIImage imageNamed:@"zhankai"] forState:UIControlStateNormal];
        }
        else
        {
             [detailBtn setImage:[UIImage imageNamed:@"shouqi_shang"] forState:UIControlStateNormal];
        }
        
        [detailBtn setTitle:@"规格明细" forState: UIControlStateNormal];
        
        [detailBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 30)];
        [detailBtn setImageEdgeInsets:UIEdgeInsetsMake(0,68, 0, 0)];
        
       
        [detailBtn setTitleColor:[UIColor colorWithRed:90.0/255.0f green:130.0/255.0f blue:26.0f/255.0f alpha:1.0] forState:UIControlStateNormal];
        [detailBtn addTarget:self action:@selector(detaiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [view addSubview:detailBtn];
        UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(10,121,ScreenWidth-20,1)];
        if (!headerModel.isOpened) {
             lineLabel.backgroundColor=[UIColor colorWithRed:238.0/255.0f green:238.0/255.0f  blue:238.0/255.0f  alpha:1];
        }
        else
        {
             lineLabel.backgroundColor=[UIColor colorWithRed:250.0/255.0f green:250.0/255.0f  blue:250.0/255.0f  alpha:1];
        }
       
        
        [view addSubview:lineLabel];
        return view;
        
        
    }
    else {
        
        UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth,122)];
        UIImageView *productImageView=[[UIImageView alloc] initWithFrame:CGRectMake(15, 20, 82, 82)];
        productImageView.layer.borderColor=[[UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1] CGColor];
        productImageView.layer.borderWidth= 1.0f;
       
        [productImageView setImageWithURL:[NSURL URLWithString:headerModel.imageUrlFull]];
        [view addSubview:productImageView];
        
        UILabel *productNameLabel=[[UILabel alloc] initWithFrame:CGRectMake(109, 20, ScreenWidth-116, 18)];
        [productNameLabel setText:headerModel.itemName];
        productNameLabel.font=[UIFont systemFontOfSize:14];
        productNameLabel.textColor=[UIColor colorWithRed:51.0/255.0f green:51.0/255.0f  blue:51.0/255.0f  alpha:1.0];
        [view addSubview:productNameLabel];
        
        UILabel *productPriceLabel=[[UILabel alloc] initWithFrame:CGRectMake(109, 46, 200, 15)];
        [productPriceLabel setText:[NSString stringWithFormat:@"¥%0.02f",[headerModel.salePrice floatValue]]];
        productPriceLabel.font=[UIFont systemFontOfSize:12];
        productPriceLabel.textColor=[UIColor colorWithRed:102.0/255.0f green:102.0/255.0f  blue:102.0/255.0f  alpha:1.0];
        [view addSubview:productPriceLabel];
        
        
        UILabel *productInvLabel=[[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth-122, 46, 110, 15)];
        //        [productInvLabel setText:[NSString stringWithFormat:@"库存 %d",[headerModel.invQty intValue]]];
        productInvLabel.font=[UIFont systemFontOfSize:12];
        productInvLabel.textColor=[UIColor colorWithRed:109.0/255.0f green:102.0/255.0f  blue:102.0/255.0f  alpha:1.0];
        NSString *str=[NSString stringWithFormat:@"库存 %d",[headerModel.invQty intValue]];
        NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:str];
        [attriString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1.0] range:NSMakeRange(0, 2)];
        
        productInvLabel.attributedText=attriString;
        productInvLabel.textAlignment=NSTextAlignmentRight;
        [view addSubview:productInvLabel];
        
        UIView *countParentView=[[UIView alloc] initWithFrame:CGRectMake(ScreenWidth-210, 68, 200, 34)];
        countParentView.layer.borderWidth=1.0;
        countParentView.layer.borderColor=[UIColor colorWithRed:240.0/255.0f green:240.0/255.0f blue:240.0/255.0f alpha:240.0/255.0f].CGColor;
        
        UIButton *subtractCountBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        [subtractCountBtn setImage:[UIImage imageNamed:@"jian_hui.png"] forState:UIControlStateNormal];
        [subtractCountBtn setFrame:CGRectMake(0, 0, 34,34)];
        subtractCountBtn.tag=section;
        [subtractCountBtn addTarget:self action:@selector(noSpecSubtractCountBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [countParentView addSubview:subtractCountBtn];
        
        UITextField *noSpecCountTextfield=[[UITextField alloc] initWithFrame:CGRectMake(31, 0, 139, 34)];
        noSpecCountTextfield.text=[NSString stringWithFormat:@" %d",[headerModel.specCount intValue]];
        noSpecCountTextfield.textColor=[UIColor colorWithRed:21.0/255.0 green:25.0/255.0 blue:32.0/255.0 alpha:1.0f];
        noSpecCountTextfield.font=[UIFont systemFontOfSize:16];
        noSpecCountTextfield.textAlignment=NSTextAlignmentCenter;
        [countParentView addSubview:noSpecCountTextfield];
        
        UIButton *addCountBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        addCountBtn.tag=section;
        [addCountBtn setImage:[UIImage imageNamed:@"jia.png"] forState:UIControlStateNormal];
        [addCountBtn setFrame:CGRectMake(160, 0, 34, 34)];
        [addCountBtn addTarget:self action:@selector(noSpecAddCountBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [countParentView addSubview:addCountBtn];
        
        [view addSubview:countParentView];
        UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(8,121,ScreenWidth-16,1)];
        
        lineLabel.backgroundColor=[UIColor colorWithRed:238.0/255.0f green:238.0/255.0f  blue:238.0/255.0f  alpha:1.0];
        
        [view addSubview:lineLabel];
        
        return view;
    }
    
}
-(void)detaiBtnClick:(UIButton *)sender
{
    parentTag=sender.tag;
    
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[sender.tag];
    headerModel.isOpened = !headerModel.isOpened;
    headerModel.modelArray=[NSMutableArray arrayWithArray:[self getHasSpecDataFromDB:headerModel.itemId senderTag:sender.tag]];;
    [headerModelArray replaceObjectAtIndex:sender.tag withObject:headerModel];
    
    
    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
   
    
}
-(NSMutableArray * )getHasSpecDataFromDB:(NSString *)itemIdStr senderTag:(NSInteger)senderTag
{
    NSMutableArray *array=[ NSMutableArray array];
    FMResultSet *resultSet=[_userDB executeQuery:@"SELECT * FROM t_UserSpec WHERE userToken = ? AND itemID = ? AND typeString = ?;" ,userToken,itemIdStr,_typeString];
    
    
    while (resultSet.next) {
        specTableViewDataModel *model=[[specTableViewDataModel alloc] init];
        
        model.itemID=[resultSet objectForColumnName:@"itemID"];
        model.itemCode=[resultSet objectForColumnName:@"itemCode"];
        model.colorSpecID=[resultSet objectForColumnName:@"colorSpecID"];
        model.sizeSpecID=[resultSet objectForColumnName:@"sizeSpecID"];
        model.specName=[resultSet objectForColumnName:@"specName"];
        
        model.specPrice=[resultSet objectForColumnName:@"specPrice"];
        model.specStock=[resultSet objectForColumnName:@"specStock"];
        model.specCount=[resultSet objectForColumnName:@"specCount"];
        
        
        [array addObject:model];
        
    }
    [resultSet close];
    //    NSLog(@"array>>><<==%@",array);
    //    [_tableView beginUpdates];
    
    // [_tableView endUpdates];
    //   [resultSet close];
    return array;
}

-(void)noSpecSubtractCountBtnClick:(UIButton *)sender
{
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[sender.tag];
    if (headerModel.specCount.intValue>1) {
        
        
        NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]];
        
        oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]-1];
        
        headerModel.specCount=oriCount;
        
        [headerModelArray replaceObjectAtIndex:sender.tag withObject:headerModel];
        
        [_tableView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationFade];
        
        [self updateNoSpecDBData:headerModel.itemId ifAdd:@"N"];
    }
    
}
-(void)noSpecAddCountBtnClick:(UIButton *)sender
{
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[sender.tag];
    if ([_typeString isEqualToString:@"WhsOut"]||[_typeString isEqualToString:@"PlaceOrder"]) {
        if ([headerModel.specCount  intValue]<[ headerModel.invQty intValue]) {
            NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]];
            oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
            headerModel.specCount=oriCount;
            [headerModelArray replaceObjectAtIndex:sender.tag withObject:headerModel];
            [_tableView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
            [self updateNoSpecDBData:headerModel.itemId ifAdd:@"Y"];
        }
        else
        {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"已超出产品库存量" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
    else
    {
        
        NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]];
        oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
        headerModel.specCount=oriCount;
        [headerModelArray replaceObjectAtIndex:sender.tag withObject:headerModel];
        [_tableView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self updateNoSpecDBData:headerModel.itemId ifAdd:@"Y"];
    }
}
-(void)updateNoSpecDBData:(NSString *)itemIDStr ifAdd:(NSString *)ifAdd
{
    
    FMResultSet *rs=[_userDB executeQuery:@"SELECT * from t_UserPlaceOrder WHERE userToken = ? AND itemID = ? AND typeString = ?;",userToken,itemIDStr, _typeString];
    if([rs next])
        
    {
        NSInteger idINDEX = [rs objectForColumnName:@"id"];
        NSString * count = [rs objectForColumnName:@"specCount"];
        
        if ([ifAdd isEqualToString:@"Y"]) {
            count=[NSString stringWithFormat:@"%d",[count intValue]+1];
        }
        else
        {
            count=[NSString stringWithFormat:@"%d",[count intValue]-1];
        }
        
        
        [_userDB executeUpdate:@"UPDATE t_UserPlaceOrder SET specCount = ?  WHERE id = ?;",count,idINDEX];
        
    }
    
    [rs close];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return headerModelArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    SelectedGoodNewHeaderDataModel *groupModel = headerModelArray[section];
    NSInteger count = groupModel.isOpened? groupModel.modelArray.count:0;
    return count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * const  ResultTableViewCellIdentifier = @"PlaceOrderSpecTableViewCell";
    PlaceOrderSpecTableViewCell *cell=( PlaceOrderSpecTableViewCell *)[tableView dequeueReusableCellWithIdentifier: ResultTableViewCellIdentifier];
    if (cell==nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"PlaceOrderSpecTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    cell.delegate=self;
    cell.addCountBtn.tag=indexPath.row;
    cell.subtractCountBtn.tag=indexPath.row;
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[indexPath.section];
    
    specTableViewDataModel *model=headerModel.modelArray[indexPath.row];
    cell.nameLabel.text= model.specName;
    cell.contentLabel.text=[NSString stringWithFormat:@"¥%0.02f  库存%d",[model.specPrice floatValue],[model.specStock intValue]];
    cell.countTextField.text=[NSString stringWithFormat:@" %d", [model.specCount intValue]];
     [cell.lineLabel setBackgroundColor:[UIColor colorWithRed:250.0/255.0f green:250.0/255.0f  blue:250.0/255.0f  alpha:1.0]];
    if (indexPath.row==headerModel.modelArray.count-1) {
        [cell.lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0f green:238.0/255.0f  blue:238.0/255.0f  alpha:1.0]];
    }
    
    
    return cell;
}
#pragma mark PlaceOrderSpecTableViewCellDelegate
-(void)SpecCellAddCountBtnClick:(NSUInteger)tag
{
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[parentTag];
    
    specTableViewDataModel *specModel=headerModel.modelArray[tag];
    if ([_typeString isEqualToString:@"WhsOut"]||[_typeString isEqualToString:@"PlaceOrder"]) {
        
        if ([specModel.specCount intValue]<[specModel.specStock intValue]) {
            NSString *oriCount=[NSString stringWithFormat:@"%d",[specModel.specCount intValue]];
            oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
            specModel.specCount=oriCount;
            [headerModel.modelArray replaceObjectAtIndex:tag withObject:specModel];
            headerModel.specCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]+1];
            [headerModelArray replaceObjectAtIndex:parentTag withObject:headerModel];
            
            NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:tag inSection:parentTag];
            [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil]  withRowAnimation:UITableViewRowAnimationFade];
            [self updateHasSpecDBData:tag ifAdd:@"Y"];
        }
        else
        {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"已超商品库存量" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        
    }
    else
    {
        NSString *oriCount=[NSString stringWithFormat:@"%d",[specModel.specCount intValue]];
        oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
        specModel.specCount=oriCount;
        [headerModel.modelArray replaceObjectAtIndex:tag withObject:specModel];
        
        headerModel.specCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]+1];
        [headerModelArray replaceObjectAtIndex:parentTag withObject:headerModel];
        
        
        NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:tag inSection:parentTag];
        [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil]  withRowAnimation:UITableViewRowAnimationFade];
        [self updateHasSpecDBData:tag ifAdd:@"Y"];
    }
}
-(void)SpecCellSubtractCountBtnClick:(NSUInteger)tag
{
    
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[parentTag];
    specTableViewDataModel *specModel=headerModel.modelArray[tag];
    NSString *oriCount=[NSString stringWithFormat:@"%d",[specModel.specCount intValue]];
    oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]-1];
    if ([oriCount intValue]>0) {
        
        specModel.specCount=oriCount;
        [headerModel.modelArray replaceObjectAtIndex:tag withObject:specModel];
        
        headerModel.specCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]-1];
        [headerModelArray replaceObjectAtIndex:parentTag withObject:headerModel];
        
        
        [self updateHasSpecDBData:tag ifAdd:@"N"];
        [self updateNoSpecDBData:headerModel.itemId ifAdd:@"N" ];
        NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:tag inSection:parentTag];
        
        
        [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil]  withRowAnimation:UITableViewRowAnimationFade];
        
        [_tableView reloadSections:[NSIndexSet indexSetWithIndex:parentTag] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    else if ([oriCount intValue]==0){
        
        [_userDB executeUpdate:@"DELETE FROM t_UserSpec WHERE userToken = ? AND itemID = ? AND colorSpecID = ? AND sizeSpecID = ? AND typeString = ?;",userToken, headerModel.itemId,specModel.colorSpecID,specModel.sizeSpecID,_typeString];
        
        [headerModel.modelArray removeObjectAtIndex:tag];
        headerModel.specCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]-1];
        [headerModelArray replaceObjectAtIndex:parentTag withObject:headerModel];
        
        [self updateNoSpecDBData:headerModel.itemId ifAdd:@"N"];
        NSIndexPath *tmpIndexpath=[NSIndexPath indexPathForRow:tag inSection:parentTag];
        
        
        [_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:tmpIndexpath, nil] withRowAnimation:UITableViewRowAnimationFade];
        if ([headerModel.specCount intValue]==0) {
            [_userDB executeUpdate:@"DELETE FROM t_UserPlaceOrder WHERE userToken = ? AND itemId = ? AND typeString = ? ;",userToken,headerModel.itemId,_typeString];
            [headerModelArray removeObjectAtIndex:parentTag];
            [_tableView reloadData];
        }
    }
}
-(void)updateHasSpecDBData:(NSInteger)senderTag ifAdd:(NSString *)ifAdd
{
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[parentTag];
    specTableViewDataModel *specModel=headerModel.modelArray[senderTag];
    
    FMResultSet *rs=[_userDB executeQuery:@"SELECT * from t_UserSpec WHERE userToken = ? AND itemID = ? AND colorSpecID = ? AND sizeSpecID = ? AND typeString = ?;",userToken, headerModel.itemId,specModel.colorSpecID,specModel.sizeSpecID,_typeString];
    //     NSLog(@"rs..==%@",rs);
    if([rs next])
        
    {
        NSInteger idINDEX = [rs objectForColumnName:@"id"];
        NSString * count = [rs objectForColumnName:@"specCount"];
        
        if ([ifAdd isEqualToString:@"Y"]) {
            count=[NSString stringWithFormat:@"%d",[count intValue]+1];
        }
        else
        {
            count=[NSString stringWithFormat:@"%d",[count intValue]-1];
        }
        
        
        [_userDB executeUpdate:@"UPDATE t_UserSpec SET specCount = ?  WHERE id = ?;",count,idINDEX];
        
    }
    [rs close];
    
}


#pragma mark  -select cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 122;
}
-(void)setAutoLayout
{
    [_titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(self.view.mas_right) ;
        make.height.equalTo(@40) ;
        make.top.equalTo(self.view.mas_top).with.offset(64);
    }];
    [_clearBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self.view.mas_right).with.offset(-10) ;
        make.height.equalTo(@40) ;
        make.width.equalTo(@30) ;
        make.top.equalTo(_titleView.mas_top) ;
    }];
    [_lastView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(self.view.mas_right) ;
        make.height.equalTo(@50) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left)  ;
        make.right.equalTo(self.view.mas_right)   ;
        make.bottom.equalTo(_lastView.mas_top) ;
        make.top.equalTo(self.view.mas_top).with.offset(40);
    }];
    
    
    [_submitConfirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(_lastView.mas_right) ;
        make.width.equalTo(@160) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(_lastView.mas_bottom);
    }];
    [_totalCountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_lastView.mas_left) ;
        make.right.equalTo(_submitConfirmBtn.mas_left) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(_lastView.mas_bottom);
    }];
    
}

- (IBAction)clearAllBtnClick:(id)sender {
    [ClearFB clearUserData:userToken typeString:_typeString];

    [headerModelArray removeAllObjects];
    [_tableView reloadData];
    _titleLabel.text=[NSString stringWithFormat:@"已选0件商品" ];
    _totalLabel.text=@"0.00";
}
- (IBAction)confirmBtnClick:(id)sender {
    NSMutableArray *productImageArray=[NSMutableArray array];
    NSMutableArray *productIDArray=[NSMutableArray array];
    NSMutableArray *productItemCodeArray=[NSMutableArray array];
//    NSMutableArray *productItemTypeArray=[NSMutableArray array];
    NSMutableArray *productNameArray=[NSMutableArray array];
    NSMutableArray *productPriceArray=[NSMutableArray array];
    NSMutableArray *productCountArray=[NSMutableArray array];
    NSMutableArray *productSpecNameArray=[NSMutableArray array];
    NSMutableArray *productSpecIDArray=[NSMutableArray array];
    NSMutableArray *productSpecPriceArray=[NSMutableArray array];
    NSMutableArray *productStockCountArray=[NSMutableArray array];
    FMResultSet *resultSet=[_userDB executeQuery:@"SELECT mainTable.itemID ,mainTable.itemCode,mainTable.itemName,mainTable.salePrice,mainTable.typeString ,mainTable.specCount AS mainCount ,mainTable.imageUrlFull , subTable.specPrice,IFNULL(subTable.specName,'') AS specName ,subTable.specCount ,subTable.specID FROM t_UserPlaceOrder mainTable LEFT JOIN t_UserSpec subTable ON mainTable.itemId = subTable.itemID AND mainTable.typeString = subTable.typeString WHERE mainTable.typeString = ? AND mainTable.userToken = ?;",_typeString,userToken];
    while (resultSet.next) {
        NSString *itemIDString=[resultSet objectForColumnName:@"itemID"];
        NSString *itemCodeString=[resultSet objectForColumnName:@"itemCode"];
        NSString *imageUrlFullString=[resultSet objectForColumnName:@"imageUrlFull"];
        NSString *itemNameString=[resultSet objectForColumnName:@"itemName"];
        NSString *salePriceString=[resultSet objectForColumnName:@"salePrice"];
//        NSString *typeStringString=[resultSet objectForColumnName:@"typeString"];
        NSString *mainCountString=[resultSet objectForColumnName:@"mainCount"];
        
        NSString *specPriceString=[resultSet objectForColumnName:@"specPrice"];
        NSString *specNameString=[resultSet objectForColumnName:@"specName"];
        NSString *specCountString=[resultSet objectForColumnName:@"specCount"];
        NSString *specIDString=[resultSet objectForColumnName:@"specID"];
        [productIDArray addObject:itemIDString];
        [productItemCodeArray addObject:itemCodeString];
        [productImageArray addObject:imageUrlFullString];
        [productNameArray addObject:itemNameString];
        [productPriceArray addObject:salePriceString];
        [productCountArray addObject:mainCountString];
        [productSpecNameArray addObject:specNameString];
        [productSpecPriceArray addObject:specPriceString];
        [productStockCountArray addObject:specCountString];
        [productSpecIDArray addObject:specIDString];
        
        
    }
    
//   NSLog(@"productItemCodeArray==%@",productItemCodeArray);
    commdity.userName=nil;
    //  shouyingViewController *shouyinVC=[[shouyingViewController alloc] init];／／1.0里面东西不管
    if (productItemCodeArray.count>0) {
        
        
        if ([commdity.gengxin isEqualToString:@""]) {//直接下单
            
            BusinessOrderExtAddViewController *shouyinVC=[[BusinessOrderExtAddViewController alloc] init];//2.0{9个参数 少2个}
            shouyinVC.headImageFullArray=productImageArray;
            shouyinVC.itemCodeArray=productItemCodeArray;
            
            shouyinVC.specNameArray=productSpecNameArray;
            shouyinVC.itemIdArray= productIDArray;
            shouyinVC.itemNameArray=productNameArray;
            shouyinVC.specIdArray=productSpecIDArray;
            shouyinVC.dealPriceArray=productPriceArray;
            shouyinVC.quantityArray=productCountArray;
            shouyinVC.saveTypeStr=_typeString;
            shouyinVC.TotalMoney=_totalLabel.text;//[NSString stringWithFormat:@"%0.02f",totalValue];
            [self.navigationController pushViewController:shouyinVC animated:YES];
            
            
        }else{
            
            //陈列入库出库盘点下单
            commdity.whsName=@"";
            commdity.content=@"";
            commdity.leixin=@"";
            commdity.code=@"";
            commdity.status=nil;
            commdity.ItemCode44= productItemCodeArray;
            commdity.Itemid44= productIDArray;
            commdity.ItemName44= productNameArray;
            commdity.ImageUrl44= productImageArray;
            commdity.Price44= productPriceArray;
            commdity.currentSpecId44=productSpecIDArray;
            commdity.how44=productCountArray;
            commdity.specName44=productSpecNameArray;
            
            if ([self.typeString isEqualToString:@"Shelf"]) {
                
                BusinessWhsInAddViewController *detailViewController = [[BusinessWhsInAddViewController alloc] init];
                detailViewController.titleName=@"确认陈列";
                detailViewController.Whs=@"Shelf";
                detailViewController.saveTypeStr=_typeString;
                [self.navigationController pushViewController:detailViewController animated:YES];
                
                
            }
            if ([self.typeString isEqualToString:@"NeedOrder"]) {
                
//                BusinessNeedOrderAddViewController *detailViewController = [[BusinessNeedOrderAddViewController alloc] init];
//                detailViewController.titleName=@"确认要货";
//                detailViewController.Whs=@"NeedOrder";
//                detailViewController.Type=@"NeedOrderType";
//                detailViewController.saveTypeStr=_typeString;
//                [self.navigationController pushViewController:detailViewController animated:YES];
                
                
            }

            if ([self.typeString isEqualToString:@"WhsOut"]) {
                BusinessWhsInAddViewController *detailViewController = [[BusinessWhsInAddViewController alloc] init];
                detailViewController.titleName=@"确认出库";
                detailViewController.Whs=@"WhsOut";
                detailViewController.Type=@"WhsOutType";
                detailViewController.saveTypeStr=_typeString;
                [self.navigationController pushViewController:detailViewController animated:YES];
                
                
            }
            
            if ([self.typeString isEqualToString:@"WhsIn"]) {
                BusinessWhsInAddViewController *detailViewController = [[BusinessWhsInAddViewController alloc] init];
                detailViewController.titleName=@"确认入库";
                detailViewController.Whs=@"WhsIn";
                detailViewController.Type=@"WhsInType";
                detailViewController.saveTypeStr=_typeString;
                [self.navigationController pushViewController:detailViewController animated:YES];
                
            }
            
            
            if ([self.typeString isEqualToString:@"CheckVouch"]) {
                
                BusinessCheckVouchAddViewController *detailViewController = [[BusinessCheckVouchAddViewController alloc] init];
                detailViewController.titleName=@"确认录入";
                detailViewController.Whs=@"CheckVouch";
                //                commdity.content=productItemTypeArray[0];
                commdity.content1=@"";
                detailViewController.saveTypeStr=_typeString;
                [self.navigationController pushViewController:detailViewController animated:YES];
            }
            
            if ([self.typeString isEqualToString:@"POrder"]) {
                
                BusinessPOrderAddViewController *detailViewController = [[BusinessPOrderAddViewController alloc] init];
                detailViewController.titleName=@"采购订单";
                detailViewController.Whs=@"POrder";
                commdity.content=@"";
                detailViewController.saveTypeStr=_typeString;
                [self.navigationController pushViewController:detailViewController animated:YES];
            }
            
            if ([self.typeString isEqualToString:@"Continue"]) {
                
                BusinessCheckVouchContinueViewController *detailViewController = [[BusinessCheckVouchContinueViewController alloc] init];
                detailViewController.titleName=@"继续盘点";
                detailViewController.Whs=@"Continue";
                detailViewController.ckvId=self.ckvId;
                detailViewController.ckvNo=self.ckvNo;
                detailViewController.whsName=self.whsName;
                detailViewController.itemTypeName=self.itemTypeName;
                detailViewController.whsId=self.whsId;
                detailViewController.itemTypeCode=self.itemTypeCode;
                detailViewController.saveTypeStr=_typeString;
                [self.navigationController pushViewController:detailViewController animated:YES];
            }
            
        }
        
    }
    else
    {
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您未选择商品" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    
    
}

-(void)setNavigation
{
    [[self rdv_tabBarController] setTabBarHidden:YES];
    
    self.navigationController.navigationBarHidden=NO;
 
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UILabel* titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,40, 23)];
    titleLabel.text=@"已选商品";
    titleLabel.font=[UIFont systemFontOfSize: 17];
    self.navigationItem.titleView=titleLabel;
    self.navigationController.navigationBar.barStyle =UIBaselineAdjustmentNone ;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    
}

-(void)BackAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
